<?php
namespace app\admin\controller;


use app\admin\common\controller\Base;
use think\facade\Session;
use think\facade\Request;
use app\admin\common\model\Admin;
use app\admin\common\service\RbacSrv;
use think\captcha\Captcha;

class Common extends Base
{
    public function imgcode()
    {
        $config = [
            'length'    =>  4,
            'useNoise'  =>  false,
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }

    public function login()
    {
        return $this->fetch('login');
    }

    public function loginDo()
    {
        $params = Request::param();

        $rule = 'app\admin\validate\Login';
        $result = $this->validate($params,$rule);

        if (true !== $result) {
            $this->error($result);
        }

        $adminInfo = Admin::where('username',$params['username'])->find();


        if (null == $adminInfo) {
            $this->error('账号不存在或密码错误!');
        }

        if ($adminInfo['password'] != md5($params['password'])) {
            $this->error('账号不存在或密码错误!');
        }

        $admin = [
            'id'        =>  $adminInfo['id'],
            'username'  =>  $adminInfo['username'],
            'remark'    =>  $adminInfo['remark'],
        ];

        Session::set('admin',$admin);

        //将用户的权限信息写入Session
        $rbac = new RbacSrv();
        $rbac->getAdminAccess($adminInfo['id']);

        $this->redirect('manage/home');
    }

    public function logout()
    {
        Session::clear();
        $this->success('退出成功','login');
    }
}
